<template>
  
       <a-flex align="center" v-if="deailsInfo.selectOptions.length > 1">
        <span>{{ $t('createtask.step.taskconfig.detailsconfig.target.index.text_qxzmb') }}</span>
        <a-select
          v-model:value="deailsInfo.id"
          style="width: 200px"
          :placeholder="$t('createtask.step.taskconfig.detailsconfig.target.index.placeholder_qxzmb')"
          :options="deailsInfo.selectOptions"
          :field-names="{ label: 'group_name', value: 'id' }"
          @change="handleChange"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        ></a-select>
      </a-flex>
    <a-tabs v-model:activeKey="sourceDetails.activeKey" >
      <a-tab-pane
        :key="index"
        :tab="item.title"
        v-for="(item, index) in sourceDetails.data"
      >
        <a-flex
          v-for="(item2, secondIndex) in item.list"
          animated
          :key="`${index}-${secondIndex}`"
          class=""
        >
          <!-- <a-flex vertical="vertical" gap="small">
                <span style="width: 140px;text-align: right;padding-right: 10px">{{ item2.label }}</span>
            </a-flex> -->
          <div style="margin-bottom: 20px; flex: 1">
            <a-row>
              <a-col
                v-for="(item3, thirdIndex) in item2.list"
                :key="`${index}-${secondIndex}-${thirdIndex}`"
                :span="item3.labelType == 'labelTitle' ? 24 : 12"
              >
                <!-- 标题栏 -->
                <h3 v-if="item3.labelType == 'labelTitle'" style="color: red">
                  {{ item3.label }}
                </h3>
                <!-- 非标题栏 -->
                <div
                  v-if="item3.labelType != 'labelTitle'"
                  style="display: flex; margin-bottom: 10px"
                >
                  <a-tooltip placement="topRight">
                    <template #title>
                      <span>{{ item3.label }}</span>
                    </template>
                    <span
                      class="text-ellipsis"
                      style="width: 150px; text-align: right"
                      v-if="item3.label"
                      >{{ item3.label }}：</span
                    >
                  </a-tooltip>

                  <!-- type为 'input_mac' -->
                  <a-row
                    v-if="item3.type == 'input_mac'"
                    style="flex: 1"
                    gutter="16"
                  >
                    <a-col
                      v-for="(el, fifthIndex) in item3.valueArr"
                      :key="`${index}-${secondIndex}-${thirdIndex}-${fifthIndex}`"
                      :span="18 / item3.valueArr.length"
                      ><a-input
                        v-model:value="item3[`value${fifthIndex}`]"
                      ></a-input
                    ></a-col>
                    <a-col :span="2">
                      <a-tooltip placement="topRight" v-if="item3.describe">
                        <template #title>
                          <span>{{ item3.describe }}</span>
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a-col>
                    <a-col :span="4"></a-col>
                  </a-row>
                  <!-- type为 'input' -->
                  <a-row
                    style="flex: 1"
                    v-if="item3.type == 'input'"
                    gutter="16"
                  >
                    <a-col :span="18"
                      ><a-input v-model:value="item3.value"></a-input
                    ></a-col>

                    <a-col :span="2">
                      <a-tooltip placement="topRight" v-if="item3.describe">
                        <template #title>
                          <span>{{ item3.describe }}</span>
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a-col>
                    <a-col :span="4"></a-col>
                  </a-row>
                  <!-- type为 'slider_mac' -->
                  <a-row
                    style="flex: 1"
                    v-if="item3.type == 'slider_mac'"
                    gutter="16"
                  >
                    <a-col :span="14"
                      ><a-slider
                        v-model:value="item3.value"
                        :max="item3.max - 0"
                        :min="item3.min - 0"
                        :step="item3.step - 0"
                    /></a-col>
                    <a-col :span="4"
                      ><a-input-number
                        v-model:value="item3.value"
                        :max="item3.max - 0"
                        :min="item3.min - 0"
                        :step="item3.step - 0"
                    /></a-col>
                    <a-col :span="2">
                      <a-tooltip placement="topRight" v-if="item3.describe">
                        <template #title>
                          <span>{{ item3.describe }}</span>
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a-col>
                    <a-col :span="4"></a-col>
                  </a-row>
                  <!-- type为 'select' -->
                  <a-row
                    style="flex: 1"
                    v-if="item3.type == 'select'"
                    gutter="16"
                  >
                    <a-col :span="18">
                      <a-select
                        style="width: 100%"
                        v-model:value="item3.value"
                        show-search
                        :options="item3.valueList"
                        :getPopupContainer="
                          (triggerNode) => triggerNode.parentNode
                        "
                      ></a-select>
                    </a-col>

                    <a-col :span="2">
                      <a-tooltip placement="topRight" v-if="item3.describe">
                        <template #title>
                          <span>{{ item3.describe }}</span>
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a-col>
                    <a-col :span="4"></a-col>
                  </a-row>
                  <!-- type为 'checkbox' -->
                  <a-row
                    style="flex: 1"
                    v-if="item3.type == 'checkbox'"
                    gutter="16"
                  >
                    <!-- <a-col :span="6"> -->

                    <a-checkbox
                      v-model:checked="item3.checkboxVS"
                      @change="changeCheck(item3)"
                      >{{ item3.checkLabel }}</a-checkbox
                    >

                    <!-- </a-col> -->
                    <div
                      style="
                        margin-top: 20px;
                        position: relative;
                        padding-left: 3vw;
                        width: 100%;
                      "
                    >
                      <!-- 第一层list代表check的儿子级 -->
                      <a-row
                        v-for="(el, checkIndex) in item3.list"
                        :key="`${index}-${secondIndex}-${thirdIndex}-${checkIndex}`"
                      >
                        <a-col :span="12"
                          ><a-checkbox
                            v-model:checked="el.checkboxVS"
                            @change="changeCheck(el)"
                            >{{ el.label }}</a-checkbox
                          ></a-col
                        >
                        <a-col
                          :span="12"
                          style="
                            margin-top: 20px;
                            line-height: 40px;
                            position: relative;
                            left: -13vw;
                            top: 10px;
                          "
                        >
                          <!-- 第二层list代表check的孙子级 -->
                          <a-row
                            v-for="(els, checkIndex) in el.list"
                            :key="`${index}-${secondIndex}-${thirdIndex}-${checkIndex}`"
                          >
                            <a-col :span="24"
                              ><a-checkbox
                                v-model:checked="els.checkboxVS"
                                @change="changeCheck(els)"
                                >{{ els.label }}</a-checkbox
                              ></a-col
                            >
                          </a-row>
                        </a-col>
                      </a-row>
                    </div>

                    <!-- <a-col :span="2">
                                    <a-tooltip placement="topRight" v-if="item3.describe"  >
                                    <template #title>
                                    <span>{{ item3.describe}}</span>
                                    </template>
                                    <QuestionCircleOutlined />
                                </a-tooltip>
                                </a-col> -->
                  </a-row>
                  <a-row
                    style="flex: 1"
                    v-if="item3.type == 'input_region'"
                    gutter="16"
                  >
                    <a-col :span="18">
                      <a-textarea
                        v-model:value="item3.value"
                        placeholder=" "
                        :auto-size="{ minRows: 2, maxRows: 5 }"
                      />
                    </a-col>
                    <a-col :span="2">
                      <a-tooltip placement="topRight" v-if="item3.describe">
                        <template #title>
                          <span>{{ item3.describe }}</span>
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a-col>
                    <a-col :span="4"></a-col>
                  </a-row>
                  <!-- <a-input  v-model:value="value" v-for="(el,fifthIndex) in item3.value" :key="`${index}-${secondIndex}-${thirdIndex}-${fifthIndex}`"></a-input> -->
                </div>
              </a-col>
            </a-row>
          </div>
        </a-flex>
      </a-tab-pane>

    </a-tabs>
    <!-- <a-flex justify="center">
      <a-button type="primary" @click="save">{{ $t('createtask.step.taskconfig.detailsconfig.target.index.text_bc') }}</a-button>
    </a-flex> -->
    <div class="flex justify-center">
          <a-button type="primary" @click="prev" style="margin-right: 10px;">上一步</a-button>
          <a-button type="primary" @click="next">下一步</a-button>
         </div>
  </template>
  

  
  <script setup>
  import {
    Card, Space, message, Modal, Empty
  } from 'ant-design-vue'
  import { ApiTwoTone, PlusCircleTwoTone, DeleteOutlined, QuestionCircleOutlined, SettingOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { ref, watch, computed, onMounted, reactive, h,defineExpose,defineComponent,defineEmits } from "vue";
  import { loadImage } from "@/hooks/loadImg";
  const { loadImgMixin, loadAllPathImg } = loadImage();
  import { cloneDeep } from 'lodash'
  import { useStore } from 'vuex';
  import * as http from "@/api/flow/createTask.js"
  import store from "@/store";
  onMounted(async () => {
    await getConfigTempId()
    await getConfigTemp()
    getConfigValue()

  
  })

  const value = ref(true)
  const sourceList = computed(() => store.state.taskInfo.sourceList)
  //目标端列表
  const targetList = computed(() => store.state.taskInfo.targetList)
  
  const sourceDetails = reactive({
    data: [],
    activeKey: '',
    a: 0,
    saveData: {}
  })
  const next = () => {
    save()
    emit('next')
  }
  const prev = () => {
    emit('prev')
  }
  const emit = defineEmits(['save','next','prev'])
  const changeSecond = (val) => {
    console.log(val, 'kkk')
  }
  const deailsInfo = reactive({
    id: null,
    selectOptions: [],
    system_status: ''
  })
  const handleChange = async () => {
    deailsInfo.system_status = deailsInfo.selectOptions.find(item => item.id == deailsInfo.id).system_status
    await getConfigTemp()

  
    // getConfigValue()
  }
  // 获取模板
  const getConfigTempId = async () => {
    let params = {
      flowId: '1751594386615',
      userId:sessionStorage.getItem('userId'),
      // flowId: rowSelectStore.flowId,
    }
    let value = await http.getConfigTempId(params)
    if (value.code == '000000') {
      // 1. 先过滤出 use_flag 为 1 的项并按 default_flag 降序
      deailsInfo.selectOptions = value.data;
      if (deailsInfo.selectOptions.length >= 1) {
        // 1. 直接查找第一个use_flag=1的项
        const targetItem = deailsInfo.selectOptions.find(item => item.use_flag == '1');
        // 2. 如果没有use_flag=1的项，再按default_flag优先级排序
        if (!targetItem) {
          const sortedItems = deailsInfo.selectOptions.sort((a, b) => {
            const priorityMap = { 2: 3, 0: 2, '-1': 1 };
            return priorityMap[b.default_flag] - priorityMap[a.default_flag];
          });
          deailsInfo.id = sortedItems[0]?.id;
          deailsInfo.system_status = sortedItems[0]?.system_status;
        } else {
          deailsInfo.id = targetItem.id;
          deailsInfo.system_status = targetItem.system_status;
        }

      }
    }
  
  }
  const rowSelectStore = store.state.taskInfo.selectMigrationFlow;
  // 目标端详细配置回显
  const getConfigTemp = async () => {
    let params = {
      userId:sessionStorage.getItem('userId'),
      flowId: '1751594386615',
      // flowId: rowSelectStore.flowId,
      confID: deailsInfo.id,
      systemStatus: deailsInfo.system_status
    }
    let value = await http.getConfigTemp(params)
    try {
      if (value.code == '000000') {
        // sourceDetails.data = JSON.parse(value.data);
        sourceDetails.data = value.data;
        console.log(sourceDetails.data, 'sourceDetails.datasourceDetails.data')
        sourceDetails.activeKey = 0;
        sourceDetails.data.forEach((item, index) => {
          // 给每个list的label赋值
          if (item.typeList) {
            item.typeList.forEach((item2, secondIndex) => {
              item.list[secondIndex].label = item2.label;
            })
          }
  
  
  
          item.list.forEach((item2, secondIndex) => {
            item2.list.forEach((item3, thirdIndex) => {
              item3.typeList.forEach((item4, fourIndex) => {
                // 改造逻辑
                // 1.list中每一个对象为一个显示信息，如果list中TypeList中labelTitle则为标题，否则是内容。
                // 2.将tylist中为内容的分组组合成一个，当前是label一项。对应表单组件类型和值是一项。将这两个合并
                if (item4.type == 'label' || item4.type == 'labelTitle') {        //针对大标题和label标题
                  item3.label = item4.label;
                  item3.labelType = item4.type;
                } else {                                                         //针对每个label对应的内容全部往上提一级合并
                  item3.valueList = item4.valueList ? item4.valueList : [];
                  item3.value = item4.value ? item4.value : '';
                  item3.type = item4.type ? item4.type : '';
                  // {
                  //     "describe": ------>描述
                  //     "file_name": ----->保存所需的参数
                  //     "list": [],
                  //     "module_name": ----->保存所需的参数
                  //     "param": ----->保存所需的参数
                  //     "typeList": ----->原先数据渲染用的list，再上述方法中已经把信息提取到当前对象
                  //     "label": ----->显示的标题/label
                  //     "labelType":  ----->labelTitle为标题，label为表单
                  //     "valueList": ----->select，slider等会用到
                  //     "value": ----->默认值
                  //     "type": ----->展示的表单类型及判断依据，共七种slider_mac,checkbox,input_region,label,input,input_mac,select
                  // }
                  // 对几种类型单独处理
                  if (item3.type == 'input_mac') {
                    item3.valueArr = item3.value ? item3.value.split(',') : [];            //将value换成数组
                    console.log(item3.value, 'item3.valueitem3.value')
                    item3.valueArr.forEach((el, fifthIndex) => {
                      item3[`value${fifthIndex}`] = el;
                    })
                  }
                  if (item3.type == 'input') { }
                  if (item3.type == 'slider_mac') {
                    item3.valueList.forEach(v => {
                      item3[v.name] = v.value;
                    })
                  }
                  if (item3.type == 'select') {
                    // item3.valueList.forEach(v=>{
                    //     item3[v.name] = v.value;
                    // })
                    item3.valueList.forEach(v => {
                      v.label = v.name
                    })
                  }
                  if (item3.type == "checkbox") {
                    item3.checkboxVS = item3.value == 'n'|| item3.value == '0' || item3.value == 'OFF' ? false : true;
                    item3.checkLabel = item4.label;
                    item3.list.forEach((item5, fifthIndex) => {
                      item5.typeList.forEach((item6, sixIndex) => {
                        item5.label = item6.label;
                        item5.type = item6.type;
                        item5.value = item6.value;
                        item5.checkboxVS = item6.value == 'n' || item6.value == '0' || item6.value == 'OFF' ? false : true;
                      })
                      item5.list.forEach((item7, fifthIndex) => {
                        item7.typeList.forEach((item8, sixIndex) => {
                          item7.label = item8.label;
                          item7.type = item8.type;
                          item7.value = item8.value;
                          item7.checkboxVS = item8.value == 'n' || item8.value == '0' || item8.value == 'OFF'? false : true;
                        })
  
                      })
                    })
                  }
                  if (item3.type == "input_region") { }
                }
              })
            })
          }
          )
          // 默认当前选中第一个
          item.activeKeySecond = 0
        })
        console.log(sourceDetails.data, 'sourceDetails.datasourceDetails.data')
      }
    } catch (error) {
      console.log(error)
      message.error($t('createtask.step.taskconfig.detailsconfig.target.index.text_qhdsc'))
    }
  
  }
  //   获取自定义配置
  const queryYloaderCustomConf = async () => {
    let params = {
      flowId: rowSelectStore.flowId,
    }
    let value = await http.queryYloaderCustomConf(params)
    if (value.code == '000000') {
      customConfigs.value = value.data;
    }
  
  }


  //   详细配置复选框改变
  const getCheckbos = (va) => {
      if(va.typeList&&va.typeList[0].checkValue){
          return va.checkboxVS ? va.typeList[0].checkValue.split(',')[0] : va.typeList[0].checkValue.split(',')[1];
      }
      return va.checkboxVS ? 'y' : 'n';
  }
  const changeCheck = (e,par) => {
    console.log(e, 'e', e.target)
      e.value = getCheckbos(e);
    e.list.forEach((item, index) => {
        item.checkboxVS = e.checkboxVS;
        item.value = getCheckbos(item);
      item.list.forEach((item2, index) => {
          item2.checkboxVS = item.checkboxVS;
          item2.value = getCheckbos(item2);
      })
    })
      if(!e.checkboxVS&&par.type=='checkbox'){//取消选中，并且有父元素
          par.checkboxVS = false;
          par.value = getCheckbos(par);
      }
  }
  // 详细配置回显
  const getConfigValue = async () => {
    let params = {
      // flowId: rowSelectStore.flowId,
      flowId: '1751594386615',
      langType: '1'
    }
    let value = await http.getConfigValue(params)
    if (value.code == '000000') {
      if (value.data) {
        let dataObj = JSON.parse(value.data.config);
        sourceDetails.data.forEach((item, index) => {
          item.list.forEach((item2, index2) => {
            item2.list.forEach((item3, index3) => {
              if (item3.param) {
                if (item3.type == "checkbox") {
                  if (Object.keys(dataObj).includes(`${item3.param}|${item3.module_name}`)) {
                    item3.value = dataObj[`${item3.param}|${item3.module_name}`];
                    item3.checkboxVS = item3.value == 'y' || item3.value == '1' || item3.value == 'ON' ? true : false;
                  }
                  item3.list.forEach((item5, fifthIndex) => {
                    if (Object.keys(dataObj).includes(`${item5.param}|${item5.module_name}|${item5.file_name}`)) {
                      item5.value = dataObj[`${item5.param}|${item5.module_name}|${item5.file_name}`]
                      item5.checkboxVS = item5.value == 'y' || item5.value == '1' || item5.value == 'ON' ? true : false;
                    }
                    item5.list.forEach((item7, fifthIndex) => {
                      if (Object.keys(dataObj).includes(`${item7.param}|${item7.module_name}|${item7.file_name}`)) {
                        item7.value = dataObj[`${item7.param}|${item7.module_name}|${item7.file_name}`]
                        item7.checkboxVS = item7.value == 'y' || item7.value == '1' || item7.value == 'ON' ? true : false;
                      }
                    })
                  })
                } else {
                  if (Object.keys(dataObj).includes(`${item3.param}|${item3.module_name}`)) {
                    item3.value = dataObj[`${item3.param}|${item3.module_name}`];
                    if (item3.type == 'input_mac') {
                      item3.valueArr = item3.value ? item3.value.split(',') : [];            //将value换成数组
                      console.log(item3.value, 'item3.valueitem3.value')
                      item3.valueArr.forEach((el, fifthIndex) => {
                        item3[`value${fifthIndex}`] = el;
                      })
                    }
                  }
                }
              }
            })
          })
        })
        console.log(dataObj, 'dataObj', sourceDetails.data)
      }

    } 
  }
  // 源端详细配置保存时数据提取
  const saveSourceDetails = () => {
  
    // 拼参格式
    // param|module_name|file_name:value,
    sourceDetails.data.forEach((item, index) => {
      item.list.forEach((item2, index2) => {
        item2.list.forEach((item3, index3) => {
          if (item3.param) {
            // 对几种类型单独处理
            if (item3.type == 'input_mac') {
              let arr = []
              item3.valueArr.forEach((el, fifthIndex) => {
                arr.push(item3[`value${fifthIndex}`])
              })
              item3.value = arr.join(',');
              sourceDetails.saveData[`${item3.param}|${item3.module_name}`] = item3.value;
            }
            if (item3.type == 'input') {
              sourceDetails.saveData[`${item3.param}|${item3.module_name}`] = item3.value;
            }
            if (item3.type == 'slider_mac') {
              sourceDetails.saveData[`${item3.param}|${item3.module_name}|${item3.file_name}`] = `${item3.value}${item3.unit}`;
            }
            if (item3.type == 'select') {
              sourceDetails.saveData[`${item3.param}|${item3.module_name}`] = item3.value;
            }
            if (item3.type == "input_region") {
              sourceDetails.saveData[`${item3.param}|${item3.module_name}`] = item3.value;
            }
            if (item3.type == "checkbox") {
              sourceDetails.saveData[`${item3.param}|${item3.module_name}`] = item3.value;
              item3.list.forEach((item5, fifthIndex) => {
                sourceDetails.saveData[`${item5.param}|${item5.module_name}|${item5.file_name}`] = item5.value;
                item5.list.forEach((item7, fifthIndex) => {
                  sourceDetails.saveData[`${item7.param}|${item7.module_name}|${item7.file_name}`] = item7.value;
                })
              })
            }
          }
        })
      })
    })
    console.log(sourceDetails, '保存的sourceDetails')
  
  }
  // 详细配置保存
  const save = async () => {

    saveSourceDetails();
  
    // 表单数据的保存
    let params = {
      flowId: '1751594386615',
      // flowId: rowSelectStore.flowId,
      langType: '1',
      pageConfig: JSON.stringify(sourceDetails.saveData),
      configId: deailsInfo.id,
      systemStatus: deailsInfo.system_status
    }
    let value = await http.saveConfigValue(params)
    if (value.code == '000000') {
      // message.success($t('createtask.step.taskconfig.dataconfig.dataconfigright.sourceconfig.advanceconfig.index.text_bcgcs'))

    } else {
      message.error(value.msg)
    }
  }
  




  
  </script>
  
  <style lang="scss" scoped>
  .text-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 26px;
  }
  
  :deep(.ant-input) {
    font-family: monospace;
    font-size: 14px;
  }
  
  :deep(.ant-form-item-explain-error) {
    margin-top: 4px;
    color: #ff4d4f;
  }
  </style>
  <style  lang="scss">
  .custom-tabs {
    :deep(.ant-tabs-left) {
      width: 200px !important; /* 或者给一个固定的宽度，如 100px */
      text-align: center; /* 根据需要调整专业对齐方式 */
    }
  }
  
  .custom-config-card {
    background: #fff;
    border-radius: 8px;
  
    :deep(.ant-card-body) {
      padding: 24px;
    }
  }
  
  .config-list {
    background: #fff;
    border-radius: 8px;
  
    &-header {
      display: flex;
      padding: 16px;
      background: #fafafa;
      border-radius: 8px 8px 0 0;
      font-weight: 500;
      color: #1f1f1f;
    }
  
    &-item {
      display: flex;
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.3s;
  
      &:hover {
        background: #fafafa;
      }
  
      &.with-error {
        background: #fff1f0;
      }
  
      &:last-child {
        border-bottom: none;
      }
    }
  }
  
  .header-item,
  .config-item {
    &.name {
      flex: 2;
      padding-right: 16px;
  
      :deep(.ant-input) {
        font-family: monospace;
      }
    }
  
    &.type {
      flex: 1;
      padding-right: 16px;
      display: flex;
      align-items: center; // 垂直居中
  
      :deep(.ant-form-item) {
        width: 100%;
        margin-bottom: 0;
      }
    }
  
    &.action {
      width: 80px;
      text-align: center;
      display: flex;
      align-items: center; // 垂直居中
      justify-content: center; // 水平居中
    }
  }
  
  // 确保表头也保持对齐
  .config-list-header {
    display: flex;
    padding: 16px;
    background: #fafafa;
    border-radius: 8px 8px 0 0;
    font-weight: 500;
    color: #1f1f1f;
  
    .header-item {
      &.type,
      &.action {
        display: flex;
        align-items: center; // 垂直居中
      }
    }
  }
  
  :deep(.ant-form-item) {
    margin-bottom: 0;
  }
  :deep(.ant-form-item-explain),
  :deep(.ant-form-item-extra) {
    min-height: 0;
    padding-top: 4px;
  }
  .ant-empty {
    padding: 32px 0;
  }
  </style>